import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router'

//创建axios实例对象
const request = axios.create({
  baseURL: '/api',
  timeout: 600000
})
//axios 的请求 request 拦截器
request.interceptors.request.use(
  (config) => { //成功回调
    let userLogin = JSON.parse(localStorage.getItem('loginUser')) // 获取到登录用户的对象
    if(userLogin){
      config.headers.token = userLogin.token
    }
    return config
  },
  (error) => { //失败回调
    return Promise.reject(error)
  }
)
//axios 的响应 response 拦截器
request.interceptors.response.use(
  (response) => { //成功回调
    return response.data
  },
  (error) => { //失败回调
    if(error.response.status === 401){
      ElMessage.error('登录超时，请重新登录')
      router.push('/login')
    }else{
      ElMessage.error('访问接口异常')
    }
  }
)
export default request